package com.app.ytong.manager.in;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.ytong.R;
import com.app.ytong.basis.BasisFragment;
import com.app.ytong.basis.Constants;
import com.app.ytong.bean.GoodsListBean;
import com.app.ytong.bean.GoodsListData;
import com.app.ytong.bean.SupplierListData;
import com.app.ytong.bean.UnitListBean;
import com.app.ytong.greendao.GreenDaoUtils;
import com.app.ytong.supplier.SupplierListActivity;
import com.app.ytong.util.MyUtils;
import com.app.ytong.view.MyNumberButton;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import my.ActivityTool;
import my.DialogUtils;

/**
 * 入库管理
 */
public class PutInFragment extends BasisFragment implements PutView {

    String fsg;
    String sna;
    PutPresenter presenter;
    static PutInFragment fragment;

    public static PutInFragment newInstance(String sort, String sna,PutPresenter presenter) {
         fragment = new PutInFragment();
        fragment.fsg = sort;
        fragment.sna = sna;
        fragment.presenter = presenter;
        return fragment;
    }


    @BindView(R.id.text_title_num)
    TextView text_title_num;

    @BindView(R.id.edit_bar_code)
    EditText edit_bar_code;


    @BindView(R.id.recycle_goods)
    RecyclerView mRecyclerGoods;
    GoodsListBean mListBean;
    private GoodListAdapter mAdapter;


    @BindView(R.id.view_settlement)
    LinearLayout view_settlement;
    @BindView(R.id.view_supplier)
    LinearLayout view_supplier;
    @BindView(R.id.text_supplier)
    TextView text_supplier;
    @BindView(R.id.view_gua_dan)
    LinearLayout view_gua_dan;


    @BindView(R.id.text_goods_weight)
    TextView text_goods_weight;
    @BindView(R.id.text_goods_num)
    TextView text_goods_num;
    @BindView(R.id.text_goods_total)
    TextView text_goods_total;

    @Override
    public void initViews() {
        switch (sna){
            case Constants.BUY_IN://采购入库
                setContentView(R.layout.buy_or_sale_fragment);
                view_supplier.setVisibility(View.VISIBLE);
                view_gua_dan.setVisibility(View.VISIBLE);
                text_supplier.setHint(Constants.PURCHASE);
                break;
            case Constants.SALE_OUT://销售出库
                setContentView(R.layout.buy_or_sale_fragment);
                view_supplier.setVisibility(View.VISIBLE);
                view_gua_dan.setVisibility(View.VISIBLE);
                text_supplier.setHint(Constants.CUSTOMER);
                break;
            case Constants.PRODUCT_IN://成品入库
            case Constants.MAKE_IN://生产入库
            case Constants.MAKE_OUT://生产出库
                setContentView(R.layout.make_in_fragment);
                view_supplier.setVisibility(View.GONE);
                break;
        }

        if(!MyUtils.getHomeSelectName().contains("饼")){
            text_title_num.setVisibility(View.GONE);
        }

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        initRecyclerGoods();
        edit_bar_code.setVisibility(View.VISIBLE);
    }


    private void initRecyclerGoods(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerGoods.setLayoutManager(layoutManager);
        mListBean = new GoodsListBean();
        setListView();
    }

    public void setData(GoodsListData data){

        if(mListBean == null){
            mListBean = new GoodsListBean();
        }
        mListBean.getList().add(data);
        setListView();
    }


    /**
     * 下面就是 listview的
     */

    public void setListView() {
        if (mAdapter == null) {
            mAdapter = new GoodListAdapter();
            mRecyclerGoods.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
            mRecyclerGoods.scrollToPosition(mAdapter.getItemCount()-1);
            notifyBottonText();
        }
    }
    private void notifyBottonText(){
        text_goods_num.setText(""+mListBean.getList().size());
        text_goods_total.setText(mListBean.getAllTotal());
        text_goods_weight.setText(mListBean.getAllWeight()+"斤");
    }

    @Override
    public void showWeight(float weight) {

    }

    @Override
    public void printMessage(String message) {
        dismissProgress();
        showToast(message);
    }

    @Override
    public void printFinish() {

    }

    @Override
    public void httpSuccess() {
        dismissProgress();
        mListBean = new GoodsListBean();
        setListView();
        DialogUtils.showSuccessrDialog(mContext,"提示！","结算成功！");
        currentSupplier = null;
        text_supplier.setText(text_supplier.getHint());
        edit_bar_code.getText().clear();
    }


    public class GoodListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        public GoodListAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            if(Constants.BUY_IN.equals(sna) || Constants.SALE_OUT.equals(sna)){
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.buy_list_item, viewGroup, false);
                return new ViewHolderBuyAndSale(view);
            }else {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.make_list_item, viewGroup, false);
                return new ViewHolderMake(view);
            }

        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
            if (viewHolder instanceof ViewHolderBuyAndSale) { // 内容
                ((ViewHolderBuyAndSale) viewHolder).bind(position);
            } else { // 尾部
                ((ViewHolderMake) viewHolder).bind(position);
            }
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolderBuyAndSale extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_unit)
            public TextView text_unit;
            @BindView(R.id.text_weight)
            public TextView text_weight;
            @BindView(R.id.text_gua)
            public TextView text_gua;
            @BindView(R.id.text_money)
            public TextView text_money;
            @BindView(R.id.edit_price)
            public EditText edit_price;
            @BindView(R.id.edit_rfid)
            public EditText edit_rfid;
            @BindView(R.id.number_button)
            public MyNumberButton number_button;

            public ViewHolderBuyAndSale(View view) {
                super(view);
                ButterKnife.bind(this, view);
                edit_price.removeTextChangedListener(mPriceWatcher);
                edit_price.addTextChangedListener(mPriceWatcher);

                edit_rfid.removeTextChangedListener(mRfidWatcher);
                edit_rfid.addTextChangedListener(mRfidWatcher);

                number_button.setWatcher(mNumWatcher);

            }

            public void bind(int position) {
                GoodsListData data = mListBean.getList().get(position);
                text_name.setText(""+data.getGna());
                text_unit.setText(""+data.getGun());
                text_weight.setText(""+data.getGwt());
                edit_price.setText(data.getPri());
                if(data.isGuadan()){
                    edit_price.setEnabled(false);
                }else {
                    edit_price.setEnabled(true);
                }
                edit_rfid.setText(data.getRfid());

                if(!MyUtils.getHomeSelectName().contains("饼")){
                    number_button.setVisibility(View.GONE);
                }
                number_button.setBuyMax(data.getMax())
                        .setInventory(data.getMax())
                        .setCurrentNumber(data.getGnu())
                        .setOnWarnListener(new MyNumberButton.OnWarnListener() {
                            @Override
                            public void onWarningForInventory(int inventory) {
                                showToast("当前库存:" + inventory);
                            }

                            @Override
                            public void onWarningForBuyMax(int buyMax) {
                                showToast("超过最大购买数:" + buyMax);
                            }
                        });
                text_gua.setVisibility(data.isGuadan()?View.VISIBLE:View.GONE);
                text_money.setText(data.getMoney());
//                notifyBottonText();

                if(data.isSelect()){
                    list_item.setBackground(mContext.getResources().getDrawable(R.drawable.base_blue_bg_corner));
                }else {
                    list_item.setBackground(mContext.getResources().getDrawable(R.drawable.base_green_line_corner));
                }
                list_item.setTag(position);
                text_unit.setTag(position);
            }

            TextWatcher mPriceWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    mListBean.setPriceChange(position, s.toString());
                    text_money.setText(mListBean.getMoneyByPosition(position));
                    notifyBottonText();
                }
            };

            TextWatcher mRfidWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    mListBean.getList().get(position).setRfid(s.toString());
                }
            };

            TextWatcher mNumWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    mListBean.getList().get(position).setGnu(Integer.valueOf(s.toString()));
                }
            };


            @OnClick(R.id.list_item)
            void onItemClick(View v){
                int position = (int) v.getTag();
                GoodsListData data = mListBean.getList().get(position);
                data.setSelect(!data.isSelect());
                notifyItemChanged(getAdapterPosition());

            }

            @OnClick(R.id.text_unit)
            void onUnitClick(View v){
                int position = (int) v.getTag();
                GoodsListData data = mListBean.getList().get(position);
                UnitListBean unitListBean = GreenDaoUtils.getUnitListBean();
                DialogUtils.showMenuDialog(mContext, unitListBean.getKnaLists(), new DialogUtils.TextResult() {
                    @Override
                    public void resultText(String text) {
                        data.setGun(text);
                        notifyItemChanged(getAdapterPosition());
                    }
                });
            }

        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolderMake extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_unit)
            public TextView text_unit;
            @BindView(R.id.text_weight)
            public TextView text_weight;
            @BindView(R.id.edit_rfid)
            public EditText edit_rfid;
            @BindView(R.id.number_button)
            public MyNumberButton number_button;

            public ViewHolderMake(View view) {
                super(view);
                ButterKnife.bind(this, view);

                edit_rfid.removeTextChangedListener(mRfidWatcher);
                edit_rfid.addTextChangedListener(mRfidWatcher);

                number_button.setWatcher(mNumWatcher);
            }

            public void bind(int position) {
                GoodsListData data = mListBean.getList().get(position);
                text_name.setText(""+data.getGna());
                text_unit.setText(""+data.getGun());
                text_weight.setText(""+data.getGwt());
                edit_rfid.setText(data.getRfid());
                if(!MyUtils.getHomeSelectName().contains("饼")){
                    number_button.setVisibility(View.GONE);
                }
                number_button.setBuyMax(data.getMax())
                        .setInventory(data.getMax())
                        .setCurrentNumber(data.getGnu())
                        .setOnWarnListener(new MyNumberButton.OnWarnListener() {
                            @Override
                            public void onWarningForInventory(int inventory) {
                                showToast("当前库存:" + inventory);
                            }

                            @Override
                            public void onWarningForBuyMax(int buyMax) {
                                showToast("超过最大购买数:" + buyMax);
                            }
                        });

//                notifyBottonText();

                if(data.isSelect()){
                    list_item.setBackground(mContext.getResources().getDrawable(R.drawable.base_blue_bg_corner));
                }else {
                    list_item.setBackground(mContext.getResources().getDrawable(R.drawable.base_green_line_corner));
                }
                list_item.setTag(data);
                text_unit.setTag(data);
            }

            TextWatcher mRfidWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    mListBean.getList().get(position).setRfid(s.toString());
                }
            };

            TextWatcher mNumWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    mListBean.getList().get(position).setGnu(Integer.valueOf(s.toString()));
                }
            };

            @OnClick(R.id.list_item)
            void onItemClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                data.setSelect(!data.isSelect());
                notifyItemChanged(getAdapterPosition());

            }

            @OnClick(R.id.text_unit)
            void onUnitClick(View view){
                GoodsListData data = (GoodsListData) view.getTag();
                UnitListBean unitListBean = GreenDaoUtils.getUnitListBean();
                DialogUtils.showMenuDialog(mContext, unitListBean.getKnaLists(), new DialogUtils.TextResult() {
                    @Override
                    public void resultText(String text) {
                        data.setGun(text);
                        notifyItemChanged(getAdapterPosition());
                    }
                });
            }

        }
    }



    @OnClick({R.id.view_settlement,R.id.view_home,R.id.view_delete,R.id.view_gua_dan,R.id.view_supplier,R.id.img_copy})
    public void btnOnClick(View v){
        switch (v  .getId()){
            case R.id.view_home:       //返回
                finish();
                break;
            case R.id.view_delete:       //删除
                DialogUtils.showWarningDialog(mContext,"是否确定删除？","删除",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        mListBean.deleteCheckList();
                        setListView();
                    }
                });
                break;
            case R.id.view_gua_dan:       //挂单
                DialogUtils.showWarningDialog(mContext,"是否确定挂单？","挂单",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        mListBean.guaDanCheckList();
                        setListView();
                        btnOnClick(view_settlement);
                    }
                });
                break;
            case R.id.view_settlement:       //结算
                if(currentSupplier == null && (sna.equals(Constants.BUY_IN)||sna.equals(Constants.SALE_OUT))){
                    showToast("请选择供应商/客户");
                    return;
                }
                if(mListBean == null || mListBean.getList().size()<1){
                    showToast("请选择商品");
                    return;
                }

                if(TextUtils.isEmpty(edit_bar_code.getText().toString().trim())){
                    showToast(""+edit_bar_code.getHint().toString());
                    return;
                }
                DialogUtils.showWarningDialog(mContext,"是否确定结算？","立即结算",new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        showLoading();
                        presenter.settlement(fsg,sna,getActivity(),mListBean,currentSupplier,edit_bar_code.getText().toString().trim());
                    }
                });
                break;
            case R.id.view_supplier:       //供应商
                Bundle extras = new Bundle();
                extras.putString("sna",sna);
                ActivityTool.skipActivityForResult(mContext, SupplierListActivity.class,extras, Constants.SUPPLIERRESULT);
                break;
            case R.id.img_copy:       //向下复制
                mListBean.copy(new GoodsListBean.CopyResult() {
                    @Override
                    public void success() {
                        setListView();
                    }

                    @Override
                    public void error(String message) {
                        showToast(message);
                    }
                },presenter.getScaleWeight());
                break;
        }
    }

    SupplierListData currentSupplier;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.SUPPLIERRESULT) {
            currentSupplier = (SupplierListData) data.getExtras().getSerializable("supplier");
            text_supplier.setText(currentSupplier.getCna());
        }
    }
}